package cos.parser;

import java.util.regex.Pattern;

import cos.entity.LyricsResponse;
import cos.entity.ParserName;
import cos.entity.Song;

public class LyricsManiaParser implements Parser {

	private static final String SITE_URL = "http://www.lyricsmania.com/";

	private final Pattern p = Pattern
			.compile("<div id='songlyrics_h' class='dn'>" + '\n');

	private final Pattern p2 = Pattern.compile("</div>");

	@Override
	public LyricsResponse getLyrics(Song song) {
		final String lyrics = parseLyricsFromSource(getPageSource(generateSongURL(song)));
		if (lyrics != null)
			return new LyricsResponse(lyrics, ParserName.LYRICS_MANIA);

		return null;
	}

	private String generateSongURL(Song song) {
		// http://www.lyricsmania.com/je_veux_lyrics_zaz.html
		return SITE_URL + song.getTitleWithoutSpaces().toLowerCase()
				+ "_lyrics_" + song.getArtistWithoutSpaces().toLowerCase()
				+ ".html";
	}

	private String getPageSource(String songURL) {
		if (songURL == null)
			return null;
		return ParserUtils.readUrlBytes(songURL);
	}

	private String parseLyricsFromSource(String source) {
		if (source == null)
			return null;
		try {
			String s = p2.split(p.split(source)[1])[0];
			return s.replaceAll("<br />", "");
		} catch (Exception e) {
			return null;
		}
	}
}
